package cool.mtc.core.util;

import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 明河
 */
public abstract class StringUtil {
    public static final String EMPTY = "";
    public static final String HYPHEN = "-";
    public static final String UNDERLINE = "_";
    public static final String POINT = ".";
    public static final String SLASH = "/";

    private static final Pattern PATTERN_UNDERSCORE = Pattern.compile("_(\\w)");

    /**
     * 判断字符串是否为空，当str为空或者空字符串时，结果为true
     */
    public static boolean isEmpty(String str) {
        return null == str || str.trim().isEmpty();
    }

    /**
     * {@link StringUtil#isEmpty(String)}的对立方法
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static String ifNull(Object obj) {
        return ifNull(obj, EMPTY);
    }

    public static String ifNull(Object obj, String replacement) {
        return null == obj ? replacement : obj.toString();
    }

    public static String ifEmpty(String str) {
        return ifEmpty(str, EMPTY);
    }

    public static String ifEmpty(String str, String replacement) {
        return isEmpty(str) ? replacement : str;
    }

    /**
     * 下划线转驼峰
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = PATTERN_UNDERSCORE.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 字节数组转16进制字符串
     */
    public static String bytesToHex(byte[] bytes) {
        return new BigInteger(1, bytes).toString(16);
    }

    /**
     * 修复路径
     * 检查路径是否以“/”结尾，如果不是，在最后加上斜杠
     */
    public static String fixPath(String path) {
        if (isEmpty(path)) {
            return SLASH;
        }
        if (path.endsWith(SLASH)) {
            return path;
        }
        return path + SLASH;
    }

    /**
     * 路径连接
     * <p>
     * 保证层级之间有”/“
     */
    public static String concatPath(String... paths) {
        if (null == paths || paths.length == 0) {
            return EMPTY;
        }
        StringBuilder pathSB = new StringBuilder();
        for (int i = 0; i < paths.length; i++) {
            String path = paths[i];
            if (isEmpty(path)) {
                continue;
            }
            // 保证目录以“/“结尾
            if (i == paths.length - 1 || path.endsWith(SLASH)) {
                pathSB.append(path);
            } else {
                pathSB.append(path).append(SLASH);
            }
            // 保证不以“/”开始
            if (i > 0 && path.startsWith(SLASH)) {
                pathSB.append(path.replaceAll("^/+", EMPTY));
            }
        }
        return pathSB.toString();
    }
}
